package com.edison.democommon.util;

import com.edison.democommon.constant.HttpHeader;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @author edison
 */
@Slf4j
public class RequestUtil {

    private static final String UNKNOWN = "unknown";

    private static final String LOCALHOST = "127.0.0.1";

    private static final String LOCALHOST_IPV6 = "0:0:0:0:0:0:0:1";
    /**
     * get request ip
     */
    public static String getRequestIp(HttpServletRequest request) {
        //when forwarding through an HTTP proxy server
        String ipAddress = request.getHeader(HttpHeader.X_FORWARDED_FOR);
        if (ipAddress == null || ipAddress.isEmpty() || UNKNOWN.equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader(HttpHeader.PROXY_CLIENT_IP);
        }
        if (ipAddress == null || ipAddress.isEmpty() || UNKNOWN.equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader(HttpHeader.WL_PROXY_CLIENT_IP);
        }
        if (ipAddress == null || ipAddress.isEmpty() || UNKNOWN.equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
            // Obtain the locally configured IP based on the network interface when accessing from the local machine.
            if (LOCALHOST.equals(ipAddress) || LOCALHOST_IPV6.equals(ipAddress)) {
                InetAddress inetAddress = null;
                try {
                    inetAddress = InetAddress.getLocalHost();
                } catch (UnknownHostException e) {
                    log.error("Get localhost error: {}",e.getMessage());
                }
                assert inetAddress != null;
                ipAddress = inetAddress.getHostAddress();
            }
        }
        // in the case of forwarding through multiple proxies, the first IP is the client’s real IP, and multiple IPs will be separated by commas (,) .
        if (ipAddress != null && ipAddress.length() > 15) {
            if (ipAddress.indexOf(",") > 0) {
                ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
            }
        }
        return ipAddress;
    }
}
